package com.ask.forMe.langchain4j.store;

import com.ask.forMe.model.dto.ChatMessages;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MongoRedisChatMemoryStore implements ChatMemoryStore {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String REDIS_KEY_PREFIX = "chat_memory:";

    // Redis缓存过期时间(秒)，例如30分钟
    private static final long CACHE_TTL_SECONDS = 1800;

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        // 1. 先尝试从Redis获取
        String redisKey = buildRedisKey(memoryId);
        String cachedJson = redisTemplate.opsForValue().get(redisKey);
        if (cachedJson != null) {
            // 命中缓存，直接返回
            return ChatMessageDeserializer.messagesFromJson(cachedJson);
        }

        // 2. Redis未命中，从MongoDB获取
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        ChatMessages chatMessages = mongoTemplate.findOne(query, ChatMessages.class);
        if (chatMessages == null) return new LinkedList<>();
        // 3. 将MongoDB结果放入Redis缓存
        String messagesJson = chatMessages.getContent();
        redisTemplate.opsForValue().set(redisKey, messagesJson, CACHE_TTL_SECONDS, TimeUnit.SECONDS);
        return ChatMessageDeserializer.messagesFromJson(chatMessages.getContent());
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        String messagesJson = ChatMessageSerializer.messagesToJson(messages);
        String redisKey = buildRedisKey(memoryId);
        // 1. 更新Redis缓存
        redisTemplate.opsForValue().set(redisKey, messagesJson, CACHE_TTL_SECONDS, TimeUnit.SECONDS);
        // 2. 更新MongoDB(可以选择同步或异步更新)
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        Update update = new Update();
        update.set("content", ChatMessageSerializer.messagesToJson(messages));
        //根据query条件能查询出文档，则修改文档；否则新增文档
        mongoTemplate.upsert(query, update, ChatMessages.class);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        String redisKey = buildRedisKey(memoryId);
        // 1. 从Redis中删除
        redisTemplate.delete(redisKey);
        // 2. 从MongoDB中删除
        Criteria criteria = Criteria.where("memoryId").is(memoryId);
        Query query = new Query(criteria);
        mongoTemplate.remove(query, ChatMessages.class);
    }

    // 构建Redis键
    private String buildRedisKey(Object memoryId) {
        return REDIS_KEY_PREFIX + memoryId.toString();
    }
}
